<template>
  <div
    v-if="dialogTableVisible1"
    :fullscreen="false"
    :modal="false"
    :show-close="false"
    :width="screenWidth + 20 + 'px'"
    :append-to-body="true"
    style="
      position: absolute;
      left: 6rem;
      margin-top: 42px;
      z-index: 10;
      background-color: white;
    "
    :close-on-click-modal="false"
  >
    <div :style="{ width: screenWidth - 96 + 'px' }">
      <div
        :style="{
          height: '40px',
          borderBottom: '1px solid #ccc',
          width: '100%',
        }"
      >
        <div style="position: absolute; right: 15px">
          <el-button @click="flushed" type="primary"> 刷新</el-button>
          <!-- <el-button v-if="Permission" @click="upButton" type="primary">
        修改业务员</el-button
      > -->
          <el-button @click="addRow" type="primary">增行</el-button>
          <el-button @click="deleteSelectedRows" type="danger">删除</el-button>
          <el-button
            type="primary"
            @click="getAllData(ruleFormRef)"
            v-if="showInsertButton"
            >保存</el-button
          >
          <el-button
            type="primary"
            @click="updateMaterialsFixed(ruleFormRef)"
            v-if="!showInsertButton"
            >保存</el-button
          >

          <el-button @click="OFFdialogTableVisible" type="danger">关闭</el-button>
        </div>
      </div>
    </div>
    <div
      ref="titleDiv"
      :style="{
        backgroundColor: 'rgba(247, 247, 247, 0.903)',
        height: 70 + 'px',
        width: screenWidth - 96 + 'px',
      }"
    >
      <el-form ref="ruleFormRef" status-icon :rules="rules" :model="form" :inline="true">
        <!-- <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">ID</label>
          <el-input
            style="width: 180px"
            v-model="form.id"
            placeholder="自动生成"
            disabled
            clearable
          />
        </el-form-item> -->
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">维度编号</label>
          <el-input
            style="width: 180px"
            v-model="form.dimensionCode"
            disabled
            placeholder="自动生成"
            clearable
          />
        </el-form-item>

        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">
            <span style="color: red; font-weight: 700">*</span>维度类型</label
          >
          <el-select
            v-model="organizationSelect"
            size="medium"
            style="width: 180px"
            clearable
            @change="clickOrganizationSelect()"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="labs" prop="name" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">
            <span style="color: red; font-weight: 700">*</span>维度名称</label
          >
          <el-input style="width: 180px" v-model="form.dimensionName" clearable />
        </el-form-item>
      </el-form>
      <el-form :model="form" class="demo-form-inline" :inline="true">
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">说明</label>
          <el-input style="width: 465px" v-model="form.description" clearable />
        </el-form-item>
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">状态</label>
          <el-switch
            v-model="form.status"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="multipleTableRef"
      :data="tableData1"
      stripe
      border
      :row-style="{ height: '20px' }"
      :height="childTableHeight - 160 + 'px'"
      style="width: 100%"
      :max-height="childTableHeight - 160 + 'px'"
      :cell-style="cellStyle1"
      @selection-change="handleSelectionChange1"
      :header-cell-style="headerCellStyle1"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="80" align="center">
        <template #default="{ $index }">
          <span>{{ $index + 1 }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label=" Id" width="180" align="center">
        <template #default="{ row, $index }">
          <el-input
            v-model="row.id"
            :style="{ height: '25px' }"
            disabled
            clearable
            placeholder="自动生成"
            align="center"
          />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="维度项目ID" width="180" align="center">
        <template #default="{ row, $index }">
          <el-input
            :readonly="true"
            @click="openEmployeeJob($index)"
            v-model="row.dimensionItemID"
            :style="{ height: '25px' }"
          />
        </template>
      </el-table-column> -->
      <el-table-column label="维度项目名称" width="180" align="center">
        <template #default="{ row, $index }">
          <el-input
            :readonly="true"
            @click="openEmployeeJob($index)"
            v-model="row.dimensionItemName"
            :style="{ height: '25px' }"
          />
        </template>
      </el-table-column>

      <el-table-column label="按钮" width="100" align="center">
        <template #default="{ row, $index }">
          <el-button
            :style="{ height: '25px' }"
            type="danger"
            size="mini"
            @click="deleteRow(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-container>
    <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
      <!-- 头部按钮 -->
      <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
        <div>
          <el-button @click="searchButton" type="primary"> 查询</el-button>
          <el-button @click="openInseart" type="success"> 新增</el-button>
          <el-button @click="deleteButton" type="danger"> 删除</el-button>
        </div>
        <!-- <div class="title">需求汇总统计表</div> -->
      </el-row>
      <div
        style="
          margin-left: 6rem;
          height: 30px;

          background: rgb(241, 244, 243);
          margin-bottom: 0;
          position: relative;
          display: flex;
          justify-content: flex-start;
        "
      >
        <el-input
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="inputName"
          placeholder="维度名称"
        >
          <template #prefix>
            <el-icon class="">
              <search />
            </el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="inputCode"
          placeholder="维度编号"
        >
          <template #prefix>
            <el-icon class="">
              <search />
            </el-icon>
          </template>
        </el-input>
      </div>
    </el-header>
    <el-container>
      <el-container>
        <el-main style="padding: 2px 2px 0 2px; margin-left: 6rem">
          <el-table
            v-loading="loading"
            ref="table"
            :data="tableData"
            border
            stripe
            :cell-style="cellStyle"
            :header-cell-style="headerCellStyle"
            @selection-change="handleSelectionChange"
            @row-dblclick="handleRowClick"
            @row-click="RowClick"
            :row-style="rowState"
            :row-key="(row: any) => row.id"
            :max-height="screenHeight"
            :height="screenHeight"
            :max-width="'300px'"
          >
            <el-table-column fixed type="index" width="80" align="center" />
            <el-table-column fixed type="selection" width="50" align="center" />
            <!-- <el-table-column prop="id" label="业务维度ID" width="120" align="center" /> -->
            <el-table-column
              prop="dimensionType"
              label="维度类型"
              width="120"
              align="center"
            />
            <el-table-column
              prop="dimensionCode"
              label="维度编码"
              width="120"
              align="center"
            />
            <el-table-column
              prop="dimensionName"
              label="维度名称"
              width="120"
              align="center"
            />
            <el-table-column prop="status" label="状态" width="120" align="center" />
            <el-table-column prop="description" label="说明" width="120" align="center" />
          </el-table>
        </el-main>
        <el-footer style="height: 20px">
          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="page"
              v-model:page-size="limit"
              :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
              :small="true"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-footer>
      </el-container>
    </el-container>
  </el-container>
  <SearchTableDialog
    ref="sea"
    @row-data="handleRowData"
    @row-datas="handleRowDatas"
  ></SearchTableDialog>
</template>
<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  ElTable,
  TableColumnCtx,
  ElMessageBox,
} from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance.ts";
import Cookies from "js-cookie";
import { format } from "date-fns";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
// crud封装组件
import * as crud from "../../components/utils/crud.ts";
import SearchTableDialog from "@/components/dialogs/SearchTableDialog.vue";
import * as notifications from "../../components/utils/notification.ts";
// 时间
// 获取当前时间
const getCurrentFormattedDateTime = () => {
  const currentDateTime = new Date();

  // 格式化当前时间
  const formattedDateTime = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  // const formattedDateTime = format(currentDateTime, "YYYY-MM-dd HH:mm:ss");

  return formattedDateTime;
};
// 获取年月日
const getCurrentFormattedDate = () => {
  const currentDateTime = new Date();

  // 格式化当前时间，只获取年月日
  const formattedDate = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });

  return formattedDate;
};
// 权限控制
const searchButtonPermissionsA = ref(false);
const menuId = ref(0);
const buttonVariables = {
  searchButtonPermissionsA,
};
const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");
  axios({
    url: "/select/Permissions/Button",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();
//权限结束
const tableData = ref([]);
const dialogTableVisible1 = ref(false);
const loading = ref(false);
const page = ref(1);
const limit = ref(50);
const total = ref(50);
const inputName = ref("");
const inputCode = ref("");
const selectBusinessDate = computed(() => ({
  page: page.value,
  limit: limit.value,
  dimensionName: inputName.value,
  dimensionCode: inputCode.value,
}));
const handleSizeChange = (val: number) => {
  selectBusinessType();
};
const handleCurrentChange = (val: number) => {
  selectBusinessType();
};
const searchButton = () => {
  selectBusinessType();
};
const selectBusinessType = async () => {
  loading.value = true;
  try {
    const res = await crud.fetchData(
      "/Bsc/select/BusinessDimensionConfiguration",
      "post",
      selectBusinessDate.value
    );
    if (res.length == 0) {
      total.value = 0;
      tableData.value = [];
      loading.value = false;
      return;
    }
    const definitionsList = res;
    total.value = definitionsList[0].total;
    loading.value = false;
    console.log(res);
    tableData.value = definitionsList.map((item: any) => ({
      status: item.status === 0 ? "未启用" : "启用",
      dimensionType: item.dimensionType === 0 ? "通用标准" : "专用标准",
      id: item.id,
      dimensionCode: item.dimensionCode,
      dimensionName: item.dimensionName,
      description: item.description,
    }));
  } catch (error) {
    loading.value = false;
    console.error("请求失败:", error);
  }
};
selectBusinessType();
// 表格
const headerCellStyle = {
  // E9E9E7
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
  // padding: "0 0 0 30px",
};
const rowState = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
    // color: "black",
  };
};
const RowClick = (row, selection) => {
  table.value.toggleRowSelection(row);
};
const selectedRows = ref([]);
const table = ref();

const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
const handleSelectionChange = (selection: any) => {
  selectedRows.value = selection;
};
const screenHeight = ref(null);
const screenWidth = ref(null);
const childTableHeight = ref(null);

const getScreenHeight = () => {
  childTableHeight.value = window.innerHeight;
  screenHeight.value = window.innerHeight - 146;
  screenWidth.value = window.innerWidth;
};
getScreenHeight();
const requestDataAsid = computed(() => ({
  deleteIdList: selectedRows.value,
}));

const deleteButton = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认删除", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }

      const res = await crud.sendRequest(
        "/Bsc/delete/BusinessDimensionConfiguration",
        "post",
        requestDataAsid.value
      );
      selectBusinessType();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

// 修改弹窗
const handleRowClick = async (row, selection) => {
  dialogTableVisible1.value = true;
  showInsertButton.value = false;
  form.id = row.id;
  form.dimensionCode = row.dimensionCode;
  form.dimensionType = row.dimensionType == "通用标准" ? 0 : 1;
  organizationSelect.value = row.dimensionType == "通用标准" ? "0" : "1";
  form.dimensionName = row.dimensionName;
  form.status = row.status === "启用" ? true : false;
  form.description = row.description;
  for (let a = 0; a < 21; a++) {
    addRow();
  }
  try {
    const res = await crud.fetchData(
      "/Bsc/select/BusinessDimensionConfiguration/Child",
      "post",
      {
        ID: row.id,
      }
    );
    if (res.length > 0) {
      for (let a = 0; a < res.length; a++) {
        tableData1.value[a].dimensionItemID = res[a].dimensionItemID;
        tableData1.value[a].dimensionItemName = res[a].dimensionItemName;
      }
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};
// 新增页面展示
const openInseart = () => {
  dialogTableVisible1.value = true;
  showInsertButton.value = true;
  for (let a = 0; a < 21; a++) {
    addRow();
  }
};

interface RuleForm {
  id: string;
  dimensionType: string;
  dimensionCode: string;
  dimensionName: string;
  status: boolean;
  descriptions: string;
}
const form = reactive<RuleForm>({
  id: "",
  dimensionType: "",
  dimensionCode: "",
  dimensionName: "",
  status: true,
  descriptions: "",
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<RuleForm>>({
  // name: [{ message: "请输入班组名称", trigger: "blur"  }],
});
// 子表展示
const cellStyle1 = ({ row, column, rowIndex, columnIndex }) => {
  return { borderColor: "#B9C9C7", padding: "0px", margin: 0 };
};
const showInsertButton = ref(true);
const multipleTableRef = ref();
const handleSelectionChange1 = (val: any[]) => {
  console.log("Selected Rows:", val);
};

const defaultRowData = {
  dimensionItemID: "",
  dimensionItemName: "",
};

const tableData1 = ref([
  {
    ...defaultRowData,
  },
  // More data...
]);
const OFFdialogTableVisible = () => {
  dialogTableVisible1.value = false;
  selectBusinessType();
  flushed();
};
const flushed = () => {
  organizationSelect.value = "";
  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
  tableData1.value = [];
  for (let a = 0; a < 21; a++) {
    addRow();
  }
};
const addRow = () => {
  tableData1.value.push({ ...defaultRowData });
};
const requestFormTable = computed(() => {
  const usefulDataArray = tableData1.value.filter((item) => item.dimensionItemID !== "");

  return {
    childList: usefulDataArray,
    ID: form.id,
    dimensionType: form.dimensionType,
    dimensionCode: form.dimensionCode,
    dimensionName: form.dimensionName,
    description: form.description,
    status: form.status ? 1 : 0,
  };
});

const updateMaterialsFixed = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认保存", "success");
    if (!result) {
      // 如果用户取消操作，则不执行更新操作
      return;
    }
    if (form.dimensionType == "") {
      notifications.showMessage("请选择维度类型", "error");
      return;
    }
    if (form.dimensionName == "") {
      notifications.showMessage("请输入维度名称", "error");
      return;
    }

    const res = await crud.sendRequest(
      "/Bsc/update/BusinessDimensionConfiguration",
      "post",
      requestFormTable.value
    );
    if (res.code == 200) {
      OFFdialogTableVisible();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const getAllData = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认保存", "success");
    if (!result) {
      // 用户点击了取消按钮，不执行保存操作
      return;
    }

    if (form.dimensionType == "") {
      notifications.showMessage("请输入维度类型", "error");
      return;
    }
    if (form.dimensionName == "") {
      notifications.showMessage("请输入维度名称", "error");
      return;
    }
    const res = await crud.sendRequest(
      "/Bsc/add/BusinessDimensionConfiguration",
      "post",
      requestFormTable.value
    );

    if (res.code == 200) {
      OFFdialogTableVisible();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const getSelectedData = () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
  console.log("Selected Data:", selectedRows);
};

const deleteSelectedRows = () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
  selectedRows.forEach((row) => {
    const index = tableData1.value.indexOf(row);
    if (index !== -1) {
      tableData1.value.splice(index, 1);
    }
  });
};

const deleteRow = (row: any) => {
  const index = tableData1.value.indexOf(row);
  if (index !== -1) {
    tableData1.value.splice(index, 1);
  }
};
const headerCellStyle1 = {
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA",
  fontWeight: "bold",
  color: "#1F2129",
  height: "40px",
  margin: 0,
  padding: 0,
};
// 弹窗
const indexEmployeeJob = ref(0);
const openEmployeeJob = (index) => {
  indexEmployeeJob.value = index;
  sea.value.dialogTableVisible = true;
  openDial();
};
const sea = ref<any>(null);
const tableDemo = ref([
  { type: "index", fixed: true, width: "60", align: "center" },
  // { type: "selection", width: "65", align: "center" },
  { prop: "itemCode", label: "项目编码", width: "120", align: "center" },
  { prop: "itemName", label: "项目名称", width: "120", align: "center" },
]);
const openDial = (row: any) => {
  sea.value.ifdynamic1 = false;
  sea.value.ifdynamic2 = false;
  sea.value.ifdynamic3 = false;
  sea.value.tableColumns = tableDemo.value;
  sea.value.apiUrl = "/select/all";
  sea.value.ifRowChoose = true;
  sea.value.compareValue = "id";
  sea.value.searchInput();
};
const handleRowData = (row) => {
  console.log('"rowData" 事件触发，行数据为：', row);
};
const handleRowDatas = (row) => {
  const index = indexEmployeeJob.value;
  for (let i = 0; i < row.length; i++) {
    const newUserId = row[i].id;
    // 验证是否存在重复的userId
    const isDuplicate = tableData1.value.some(
      (item) => item.dimensionItemID === newUserId
    );
    if (isDuplicate) {
      notifications.showMessage(
        `已经存在 userId 为 ${newUserId} 的记录，不能重复添加，序号为 ${i + 1}`,
        "error"
      );

      return;
    }
    tableData1.value[index + i].dimensionItemID = row[i].id;
    tableData1.value[index + i].dimensionItemName = row[i].itemName;
  }
};

// 查询下拉框;
// 组织类型
const options = reactive([
  {
    value: "Option1",
    label: "Option1",
  },
]);

const transformResToOptions = (res) => {
  return res.map((item) => {
    return {
      value: item.code,
      label: item.codeName,
    };
  });
};
const selectSystem_parameter_sub_tableDate = reactive({
  tableName: "BusinessDimensionConfigurationMainTable",
  field: "dimensionType",
});
const organizationSelect = ref("");

const selectSystem_parameter_sub_table = async () => {
  try {
    const res = await crud.fetchData(
      "/BusinessType/select/System_parameter_sub_table",
      "post",
      selectSystem_parameter_sub_tableDate
    );
    options.splice(0, options.length, ...transformResToOptions(res));
  } catch (error) {
    console.error("请求失败:", error);
  }
};
selectSystem_parameter_sub_table();
const isDisabled = ref(true);
const clickOrganizationSelect = () => {
  form.dimensionType = organizationSelect.value;
};
</script>
<style scoped>
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.down-tree ::v-deep .el-tree-node.is-expanded > .el-tree-node__children {
  display: inline;
}

.down-tree {
  height: 100%;
}

.demo-pagination-block {
  float: right;
}

.custom-dialog {
  position: fixed;
  top: 10em;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.labs {
  margin-bottom: 0px;
}

.lab {
  background-color: rgba(247, 247, 247, 0.903);
  /* border-radius: 5px; */
  text-align: center;
  margin-bottom: 0px;
  text-align: right;
}
</style>
